package com.ukao.cashregister.ui.stokin;


import android.os.Build;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.annotation.RequiresApi;
import android.support.v7.widget.AppCompatCheckBox;
import android.support.v7.widget.Toolbar;
import android.text.Spannable;
import android.text.SpannableString;
import android.text.TextUtils;
import android.text.style.AbsoluteSizeSpan;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CompoundButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.gprinterio.GpDevice;
import com.ukao.cashregister.R;
import com.ukao.cashregister.base.MvpFragment;
import com.ukao.cashregister.bean.BalanceBean;
import com.ukao.cashregister.bean.Coupons;
import com.ukao.cashregister.bean.PayInfoBean;
import com.ukao.cashregister.bean.ReceiptBean;
import com.ukao.cashregister.bean.RechargeBean;
import com.ukao.cashregister.bean.UserInfoBean;
import com.ukao.cashregister.consts.GlobalConsts;
import com.ukao.cashregister.dialog.BalanceDialogFragment;
import com.ukao.cashregister.dialog.CouponsDialogFragment;
import com.ukao.cashregister.dialog.RechargeDialogFragment;
import com.ukao.cashregister.dialog.SelectNumDialogFragment;
import com.ukao.cashregister.eventbus.PayAmountEvent;
import com.ukao.cashregister.eventbus.PayEvent;
import com.ukao.cashregister.eventbus.UserInfoEvent;
import com.ukao.cashregister.listener.OnDialogSureClickListener;
import com.ukao.cashregister.pesenter.GatheringPesenter;
import com.ukao.cashregister.printer.PrintMiuiHelper;
import com.ukao.cashregister.printer.PrinterReceipt;
import com.ukao.cashregister.ui.MainActivity;
import com.ukao.cashregister.ui.createOrders.CreateOrdersFragment;
import com.ukao.cashregister.ui.createOrders.UserInfoFragment;
import com.ukao.cashregister.ui.orderQuiry.OrderQuiryDetailFragment;
import com.ukao.cashregister.ui.orderQuiry.OrderManageFragment;
import com.ukao.cashregister.ui.sendFactory.sendFactoryFragment;
import com.ukao.cashregister.utils.CheckUsbDeviceUtils;
import com.ukao.cashregister.utils.CheckUtils;
import com.ukao.cashregister.utils.DecimalUtil;
import com.ukao.cashregister.utils.DensityUtils;
import com.ukao.cashregister.utils.T;
import com.ukao.cashregister.view.GatheringView;
import com.ukao.cashregister.widget.HideLinearLayout;
import com.ukao.cashregister.widget.StateButton;

import org.greenrobot.eventbus.Subscribe;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnCheckedChanged;
import butterknife.OnClick;
import butterknife.Unbinder;
import me.yokeyword.fragmentation.SupportFragment;

import static com.ukao.cashregister.R.id.balance_radio_layout;
import static com.ukao.cashregister.R.id.couponAmt_layout;
import static com.ukao.cashregister.R.id.preferential_radio_layout;


/**
 * 收款
 */
public class GatheringFragment extends MvpFragment<GatheringPesenter> implements GatheringView {

    private static final String ARG_PARAM1 = "param1";
    private static final String ARG_PARAM2 = "param2";
    @BindView(R.id.back_layout)
    LinearLayout backLayout;
    @BindView(R.id.user_info_toolbar)
    Toolbar userInfoToolbar;
    @BindView(R.id.recharge_name)
    TextView rechargeName;
    @BindView(R.id.recharge_balance)
    TextView rechargeBalance;
    @BindView(R.id.recharge_right_tab1)
    RadioButton rechargeRightTab1;
    @BindView(R.id.recharge_right_tab2)
    RadioButton rechargeRightTab2;
    @BindView(R.id.recharge_hite)
    TextView rechargeHite;
    @BindView(R.id.no_activity)
    TextView noActivity;
    @BindView(R.id.easy_recharge)
    TextView easyRecharge;
    @BindView(R.id.recharge_dialog_name)
    TextView rechargeDialogName;

    @BindView(R.id.recharge_dialog_layout)
    LinearLayout rechargeDialogLayout;
    @BindView(R.id.recharge_layout)
    LinearLayout rechargeLayout;
    @BindView(R.id.orderPrice)
    TextView orderPrice;
    @BindView(R.id.carriage)
    TextView carriage;
    @BindView(R.id.textView6)
    TextView textView6;
    @BindView(R.id.modifyPrice)
    TextView modifyPrice;
    @BindView(R.id.modifyPrice_layout)
    RelativeLayout modifyPriceLayout;
    @BindView(R.id.paymentPrice)
    TextView paymentPrice;   //设置应收款金额
    @BindView(R.id.couponAmt)
    TextView tvCouponAmt;    //设置优惠卷的金额

    @BindView(R.id.usable_balance)
    TextView usableBalance;
    @BindView(R.id.balance)
    TextView vipCardBalance;
    @BindView(R.id.enabled_imageview)
    ImageView enabledImageview;
    @BindView(R.id.enabled_checkBox)
    AppCompatCheckBox enabledCheckBox;
    @BindView(R.id.orders_layout)
    LinearLayout ordersLayout;
    @BindView(R.id.sure_gathering_btn)
    TextView sureGatheringBtn;
    @BindView(R.id.should_Price)
    TextView shouldPrice;
    @BindView(R.id.should_pay_layout)
    LinearLayout shouldPayLayout;
    @BindView(R.id.gathering_layout)
    RelativeLayout gatheringLayout;
    @BindView(R.id.sure_gather_txt)
    TextView sureGatherTxt;
    @BindView(R.id.gather_succeed_txt)
    TextView gatherSucceedTxt;
    @BindView(R.id.print_btn)
    StateButton printBtn;
    @BindView(R.id.storage_btn)
    StateButton storageBtn;
    @BindView(R.id.ordier_list_btn)
    StateButton ordierListBtn;
    @BindView(R.id.ordier_details_btn)
    StateButton ordierDetailsBtn;
    @BindView(R.id.place_order_btn)
    StateButton placeOrderBtn;
    @BindView(R.id.enter_factory_btn)
    StateButton enterFactoryBtn;
    @BindView(R.id.button_layout)
    LinearLayout buttonLayout;

    @BindView(R.id.order_detail_tab1)
    RelativeLayout orderDetailTab1;
    @BindView(R.id.order_detail_tab2)
    RelativeLayout orderDetailTab2;
    @BindView(R.id.order_detail_tab3)
    RelativeLayout orderDetailTab3;
    @BindView(R.id.order_detail_tab4)
    RelativeLayout orderDetailTab4;

    @BindView(R.id.pay_layout)
    LinearLayout payLayout;


    @BindView(R.id.pay_type_two)
    LinearLayout payTypeTwo;
    @BindView(R.id.pay_succeed_layout)
    RelativeLayout paySucceedLayout;
    @BindView(R.id.frame_layout)
    HideLinearLayout frameLayout;
    @BindView(R.id.usable_balance_msg)
    TextView tvBalancePay;
    @BindView(R.id.usable_balance_two)
    TextView tvUsableBalance;


    @BindView(R.id.preferential_balance)
    TextView preferentialBalance;
    @BindView(R.id.preferential_payRatio)
    TextView preferentialPayRatio;


    @BindView(R.id.cloth_layout)
    LinearLayout clothLayout;
    @BindView(R.id.recharge_dialog_more)
    TextView rechargeDialogMore;
    @BindView(R.id.couponAmt_layout)
    LinearLayout couponAmtLayout;
    @BindView(R.id.pay_type_one)
    LinearLayout vipCardBalanceLayout;
    @BindView(R.id.balance_radio_button)
    AppCompatCheckBox balanceRadioButton;
    @BindView(R.id.balance_should_pice)
    TextView balanceShouldPice;
    @BindView(R.id.balance_radio_layout)
    LinearLayout balanceRadioLayout;
    @BindView(R.id.preferential_msg)
    TextView preferentialMsg;
    @BindView(R.id.preferential_radio_button)
    AppCompatCheckBox preferentialRadioButton;
    @BindView(R.id.preferential_should_pice)
    TextView preferentialShouldPice;
    @BindView(R.id.preferential_radio_layout)
    LinearLayout preferentialRadioLayout;
    @BindView(R.id.pay_unionpay)
    TextView payUnionpay;


    private PayInfoBean mPayInfo;

    private Unbinder unbinder;


    private SupportFragment[] mFragments = new SupportFragment[4];
    private BalanceBean mBalanceBean;
    private String orderId = "";
    private String userId;
    private boolean isloadSucceed;
    private String bacetitle;
    private Serializable mParameter;
    private ArrayList<RechargeBean> mRechargeData;
    private boolean isRechargeEnter;
    private UserInfoBean.UserBean mUserBean;
    private String rechargeAmount = ""; /*充值的金額*/
    private String rechargeAmount1;
    private int totalBalance;  //可用余额
    private int lastPosition;
    private PayInfoBean.UPayCardBean uPayCard;
    private String withActive;
    private boolean isExistCpnRelId;
    private  String  receivableAmount;  //应收款金额

    public static GatheringFragment newInstance(String param1, PayInfoBean mPayInfo, String bacetitle) {
        GatheringFragment fragment = new GatheringFragment();
        Bundle args = new Bundle();
        args.putString(ARG_PARAM1, param1);
        args.putSerializable(ARG_PARAM2, mPayInfo);
        args.putString(ARG_PARAM3, bacetitle);
        fragment.setArguments(args);
        return fragment;
    }

    /**
     * 入库 收款按钮调用段代码
     * @param param1
     * @param backtitle
     * @return
     */
    public static GatheringFragment newInstance(String param1, String backtitle) {
        GatheringFragment fragment = new GatheringFragment();
        Bundle args = new Bundle();
        args.putString(ARG_PARAM1, param1);
        args.putString(ARG_PARAM3, backtitle);
        fragment.setArguments(args);
        return fragment;
    }


    public static GatheringFragment newInstance(ArrayList<RechargeBean> mList, UserInfoBean.UserBean UserBean) {
        GatheringFragment fragment = new GatheringFragment();
        Bundle args = new Bundle();
        args.putSerializable(ARG_PARAM4, mList);
        args.putSerializable(ARG_PARAM2, UserBean);
        fragment.setArguments(args);
        return fragment;
    }


    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            mParameter = getArguments().getSerializable(ARG_PARAM4);
            if (!CheckUtils.isNull(mParameter)) { /*充值界面*/
                mRechargeData = (ArrayList<RechargeBean>) mParameter;
                mUserBean = (UserInfoBean.UserBean) getArguments().getSerializable(ARG_PARAM2);
                isRechargeEnter = true;
            } else {  /*订单界面*/
                isRechargeEnter = false;
                orderId = getArguments().getString(ARG_PARAM1);
                Serializable mSerializable = getArguments().getSerializable(ARG_PARAM2);
                bacetitle = getArguments().getString(ARG_PARAM3);
                if (!CheckUtils.isNull(mSerializable)){
                    mPayInfo = (PayInfoBean) mSerializable;
                }
            }
        }
    }

    @Override
    protected GatheringPesenter createPresenter() {
        return new GatheringPesenter(this);
    }


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_gathering, container, false);
        unbinder = ButterKnife.bind(this, view);
        return view;
    }
    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        initView();
        initListener();
        if (!isRechargeEnter) {
            //收款就会进入
            mvpPresenter.gathering(orderId);
        }
    }

    @Override
    protected void initListener() {
        enabledCheckBox.setOnCheckedChangeListener(mOnCheckedChange);
        balanceRadioButton.setClickable(false);
        preferentialRadioButton.setClickable(false);
    }


    private CompoundButton.OnCheckedChangeListener mOnCheckedChange = new CompoundButton.OnCheckedChangeListener() {
        @Override
        public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
            if (CheckUtils.isNull(mPayInfo)){
                return;
            }
            if (enabledCheckBox == buttonView) {
                reckonShouldPrice();
            }
        }
    };
    /**
     * 设置使用优选样式
     */
    private void setUpayStyles() {
        int shouldPrice;
        if(preferentialRadioButton.isChecked()){
            mPayInfo.setUseUPay(true);   //使用了优付卡支付
            mPayInfo.setPayBalance(0);
            if(!couponAmtLayout.isEnabled()){  //不能与优惠卷同时使用时
                int useBalance;
                int mRatioPice = (mPayInfo.getPayablePrice() * uPayCard.getPayRatio()) / 100;  /*得到可支付比例金额*/
                int uPayPayPice = mRatioPice - uPayCard.getBalance();/*还应收款金额*/
                if (uPayPayPice > 0) {  /*余额不足*/
                    shouldPrice = mPayInfo.getPayablePrice() - uPayCard.getBalance();
                    mPayInfo.setShouldPrice(shouldPrice);
                    useBalance = uPayCard.getBalance();
                } else { /*余额充足*/
                    useBalance = mRatioPice;
                    if (mPayInfo.getPayablePrice() - mRatioPice > 0) {/*应收款*/
                        shouldPrice = mPayInfo.getPayablePrice() - mRatioPice;
                    } else {
                        shouldPrice = 0;
                    }
                }
                preferentialShouldPice.setText("抵扣" + CheckUtils.isEmptyNumber(useBalance) + "元");
                mPayInfo.setShouldPrice(shouldPrice);
                setShouldPriceStyle(shouldPrice);
            }else { // 计算能与优惠卷同时使用价格
                int couponAmt1 = mPayInfo.getCouponAmt();
                int remainPrice = mPayInfo.getPayablePrice() - couponAmt1;  /*优惠后的金额*/
                int useBalance;
                int mRatioPice = (remainPrice * uPayCard.getPayRatio()) / 100;  /*得到可支付比例金额*/
                int uPayPayPice = mRatioPice - uPayCard.getBalance();/*还应收款金额*/
                if (uPayPayPice > 0) {  /*余额不足*/
                    shouldPrice = remainPrice - uPayCard.getBalance();
                    mPayInfo.setShouldPrice(shouldPrice);
                    useBalance = uPayCard.getBalance();
                } else { /*余额充足*/
                    useBalance = mRatioPice;
                    if (remainPrice - mRatioPice > 0) {/*应收款*/
                        shouldPrice = remainPrice - mRatioPice;
                    } else {
                        shouldPrice = 0;
                    }
                }
                preferentialShouldPice.setText("抵扣" + CheckUtils.isEmptyNumber(useBalance) + "元");
                mPayInfo.setShouldPrice(shouldPrice);
                setShouldPriceStyle(shouldPrice);
            }
        }else {
            mPayInfo.setPayBalance(0);
            mPayInfo.setUseUPay(false);  //没有使用优付卡支付
            shouldPrice = mPayInfo.getPayablePrice() - mPayInfo.getCouponAmt();
            mPayInfo.setShouldPrice(shouldPrice);
            preferentialShouldPice.setText("");
            setShouldPriceStyle(shouldPrice);

        }
    }


    /**
     * 查询订单信息返回数据
     */
    private void initData() {

        orderId = mPayInfo.getOrderId();
        userId = mPayInfo.getUserId();
        mvpPresenter.userExtbalance(userId, true);
    }
    @Override
    protected void initView() {
        isloadSucceed = false;
        storageBtn.setText(bacetitle);
        rechargeFillData();
        SupportFragment firstFragment = findFragment(AlipayWeChatFragment.class);
        if (firstFragment == null) {
            mFragments[0] = AlipayWeChatFragment.newInstance(0, isRechargeEnter ? userId : "", isRechargeEnter ? rechargeAmount : "", withActive);
            mFragments[1] = AlipayWeChatFragment.newInstance(1, isRechargeEnter ? userId : "", isRechargeEnter ? rechargeAmount : "", withActive);
            mFragments[2] = CashFragment.newInstance(orderId, userId, rechargeAmount, withActive);
            mFragments[3] = UnionpayFragment.newInstance(orderId, userId, rechargeAmount, withActive);
            loadMultipleRootFragment(R.id.frame_layout, 0,
                    mFragments[0],
                    mFragments[1],
                    mFragments[2],
                    mFragments[3]);
        } else {
            mFragments[0] = firstFragment;
            mFragments[1] = findFragment(AlipayWeChatFragment.class);
            mFragments[2] = findFragment(CashFragment.class);
            mFragments[3] = findFragment(UnionpayFragment.class);
        }
    }


    private void rechargeFillData() {
        if (isRechargeEnter) {   /*充值*/
            rechargeLayout.setVisibility(View.VISIBLE);
            ordersLayout.setVisibility(View.GONE);
            mvpPresenter.getPaymentConfig();
            if (!CheckUtils.isNull(mUserBean)) {
                UserInfoBean.UserBean.InfoBeanX minfo = mUserBean.getInfo();
                userId = minfo.getId();
                rechargeName.setText(minfo.getPhone() + " " + minfo.getName());
                mvpPresenter.userExtbalance(minfo.getId(), true);
                if (!CheckUtils.isEmpty(mRechargeData)) {
                    for (RechargeBean rechargeBean : mRechargeData) {
                        rechargeBean.setCheck(false);
                    }
                    RechargeBean item = mRechargeData.get(0);
                    item.setCheck(true);
                    rechargeDialogLayout.setVisibility(View.VISIBLE);
                    noActivity.setVisibility(View.GONE);
                    fillRechargeData(item);
                } else {
                    setRechargePiceStyles("0", false);
                    noActivity.setVisibility(View.VISIBLE);
                }
            }
        }
    }


    @OnCheckedChanged({R.id.recharge_right_tab1, R.id.recharge_right_tab2})
    public void onChekChanged(CompoundButton view, boolean check) {
        if (check) {
            switch (view.getId()) {
                case R.id.recharge_right_tab1:
                    rechargeHite.setText("活动方案充值");
                    easyRecharge.setVisibility(View.GONE);
                    if (!CheckUtils.isEmpty(mRechargeData)) {
                        rechargeDialogLayout.setVisibility(View.VISIBLE);
                        noActivity.setVisibility(View.GONE);
                    } else {
                        rechargeDialogLayout.setVisibility(View.GONE);
                        noActivity.setVisibility(View.VISIBLE);
                    }
                    if (!CheckUtils.isEmpty(rechargeAmount)) {
                        setRechargePiceStyles(rechargeAmount, false);
                    } else {
                        setRechargePiceStyles("0", false);
                    }
                    break;
                case R.id.recharge_right_tab2:
                    showBalanceDialog();
                    rechargeHite.setText("");
                    rechargeDialogLayout.setVisibility(View.GONE);
                    noActivity.setVisibility(View.GONE);
                    if (!CheckUtils.isEmpty(rechargeAmount1)) {
                        setRechargePiceStyles(rechargeAmount1, true);
                        easyRecharge.setText("零散金额：" + rechargeAmount1 + "元");
                        easyRecharge.setVisibility(View.VISIBLE);
                    } else {
                        noActivity.setVisibility(View.INVISIBLE);
                        setRechargePiceStyles("0", true);
                    }
                    break;
            }
        }
    }


    /**
     * 充值对话框
     */
    public void showRechargeDialog() {
        RechargeDialogFragment tag = new RechargeDialogFragment();
        Bundle mBundle = new Bundle();
        mBundle.putSerializable(ARG_PARAM1, mRechargeData);
        tag.setArguments(mBundle);
        tag.setOnSureClickListener(mOnDialogSure);
        tag.show(getChildFragmentManager(), RechargeDialogFragment.class.getName());
    }

    private OnDialogSureClickListener mOnDialogSure = new OnDialogSureClickListener() {
        @Override
        public void onSureItemClick(Object message) {
            RechargeBean mRechargeBean = (RechargeBean) message;
            rechargeAmount = mRechargeBean.getCount();
            fillRechargeData(mRechargeBean);
            setRechargePiceStyles(rechargeAmount, false);
        }
    };


    /**
     * 设置充值金额样式
     *
     * @param isScattered 是否是零散充值
     * @param amount      充值金额
     */
    private void setRechargePiceStyles(String amount, boolean isScattered) {

        if (CheckUtils.isEmpty(amount) || amount.indexOf(".") == -1) {
            amount = DecimalUtil.multiply(amount, "1");
        }

        if (amount.indexOf(".") == -1) return;
        String strAmount = "￥" + amount;
        Spannable span = new SpannableString(strAmount);
        span.setSpan(new AbsoluteSizeSpan(CheckUtils.isMIUIDevices() ? 80 : 120), 1, strAmount.indexOf("."), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
        shouldPrice.setText(span);
        withActive = isScattered ? "0" : "1";
        HashMap map = new HashMap();
        map.put(ARG_PARAM1, amount);
        map.put(ARG_PARAM2, withActive);//1.参数活动 0.不参数活动
        PayAmountEvent.postHasData(PayAmountEvent.Message.recharge, map);
    }
    @Override
    public void onDestroyView() {
        super.onDestroyView();
        unbinder.unbind();
    }


    @Override
    protected boolean useEventBus() {
        return true;
    }

    @RequiresApi(api = Build.VERSION_CODES.N)
    @Subscribe
    public void onEvent(PayEvent event) {
        switch (event.getMessage()) {
            case PAY_SUCCEED:
                setFragmentResult(RESULT_OK, null);
                if (!isRechargeEnter) {
                    buttonLayout.setVisibility(View.VISIBLE);
                } else {
                    UserInfoEvent.postNoData(UserInfoEvent.Message.USEINFO);
                }
                dismissProgressDialog();
                finish();
                break;
            case coupon:   //优惠卷事件
                this.setCouponsStyle(mPayInfo.getCpnRelId(),mPayInfo.getCouponAmt());
                this.setVipCardBalanceAndPreferentialPayEnabled();  //设置余额支付和优付卡是否能点击
                if (preferentialRadioButton.isChecked()) {
                    setUpayStyles();
                } else {
                    reckonShouldPrice();
                }
                break;
            case recharge:
                rechargeDialogLayout.setVisibility(View.GONE);
                noActivity.setVisibility(View.GONE);
                easyRecharge.setVisibility(View.VISIBLE);
                rechargeAmount1 = (String) event.getData();
                easyRecharge.setText("零散金额：" + rechargeAmount1 + "元");
                setRechargePiceStyles(rechargeAmount1, true);/*零散充值*/
                break;
            case  look_use:
              final UserInfoBean.UserBean        mUserInfoBean= (UserInfoBean.UserBean) event.getData();
                if (mUserInfoBean==null)return;
                popTo(GatheringFragment.class, true, new Runnable() {
                @Override
                public void run() {
                    start(UserInfoFragment.newInstance("", mUserInfoBean), SINGLETASK);
                }
            });
                break;
        }


    }



    /**
     * 计算余额支付和会员卡余额支付应收款
     * 支付金额    优惠券  余额
     */
    private void reckonShouldPrice() {
        if (enabledCheckBox.isChecked() || balanceRadioButton.isChecked()) {
            int remainPrice = mPayInfo.getPayablePrice() - mPayInfo.getCouponAmt();/*得到优惠后的金额*/
            int useBalance;
            if (totalBalance - remainPrice < 0) { /*余额不足*/
                useBalance = totalBalance;
            } else {  /*余额充足*/
                useBalance = remainPrice;
            }
            mPayInfo.setPayBalance(useBalance);//获得 要支付的余额
            int shouldPayPrice = mPayInfo.getPayablePrice() - useBalance - mPayInfo.getCouponAmt();
            mPayInfo.setShouldPrice(shouldPayPrice); //设置还要支付的金额
            setShouldPriceStyle(mPayInfo.getShouldPrice());
            if (vipCardBalanceLayout.getVisibility() == View.VISIBLE) {  /*第一种支付类型*/
                vipCardBalance.setText(useBalance > 0 ? "-" + CheckUtils.isEmptyNumber(useBalance) : "");/*会员卡余额*/
            } else {
                balanceShouldPice.setText(useBalance > 0 ? "抵扣" + CheckUtils.isEmptyNumber(useBalance) + "元" : "");
            }
        } else {
            preferentialShouldPice.setText("");
            balanceShouldPice.setText("");
            vipCardBalance.setText("");
            mPayInfo.setPayBalance(0);
            int remainPrice = mPayInfo.getPayablePrice() - mPayInfo.getCouponAmt();/*应收款*/
            mPayInfo.setShouldPrice(remainPrice);
            setShouldPriceStyle(remainPrice >= 0 ? remainPrice : 0);
        }
    }

    /**
     * 设置收款样式
     *
     * @param price 还应收款金额
     */
    private void setShouldPriceStyle(int price) {
        if (price > 0) {
            gatheringLayout.setBackgroundResource(R.drawable.shape_button_red_select);  //红色
            setPayVisibility(false);
        } else {
            gatheringLayout.setBackgroundResource(R.drawable.blue_bt_selector); //蓝色
            setPayVisibility(true);
        }
        String paidPrice = "￥" + CheckUtils.isEmptyNumber(price);
        if (price > 0) {
            int index = paidPrice.indexOf(".");
            if (index != -1) {
                Spannable span = new SpannableString(paidPrice);
                span.setSpan(new AbsoluteSizeSpan(CheckUtils.isMIUIDevices() ? 80 : 120), 1, index, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
                shouldPrice.setText(span);
                PayAmountEvent.postHasData(PayAmountEvent.Message.PAY_COUNT, mPayInfo);
            }
        }

    }

    /**
     * @param isNotnough 是否余额显示
     */
    private void setPayVisibility(boolean isNotnough) {
        shouldPayLayout.setVisibility(isNotnough ? View.GONE : View.VISIBLE);
        payLayout.setVisibility(isNotnough ? View.GONE : View.VISIBLE);
        sureGatheringBtn.setVisibility(isNotnough ? View.VISIBLE : View.GONE);
        sureGatherTxt.setVisibility(isNotnough ? View.VISIBLE : View.GONE);
        paySucceedLayout.setVisibility(isNotnough ? View.VISIBLE : View.GONE);
    }

    @OnClick({R.id.easy_recharge, R.id.order_detail_tab1, R.id.order_detail_tab2, couponAmt_layout, balance_radio_layout, preferential_radio_layout,
            R.id.order_detail_tab3, R.id.order_detail_tab4, R.id.gathering_layout, R.id.back_layout, R.id.enter_factory_btn,
            R.id.print_btn, R.id.storage_btn, R.id.ordier_list_btn, R.id.ordier_details_btn, R.id.place_order_btn, R.id.recharge_dialog_layout})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.enter_factory_btn: /*进厂*/

                popTo(GatheringFragment.class, true, new Runnable() {
                    @Override
                    public void run() {
                        start(sendFactoryFragment.newInstance("", ""));

                    }
                });
                break;

            case R.id.balance_radio_layout: //点击了余额支付布局
                if (!balanceRadioButton.isChecked() && !CheckUtils.isNull(mPayInfo)) {
                    balanceRadioButton.setChecked(true);
                    if(preferentialRadioButton.isChecked()){
                        //如果优付卡选中了 设置为不使用优付卡
                        mPayInfo.setUseUPay(false);
                        preferentialRadioButton.setChecked(false);
                        preferentialShouldPice.setText("");
                    }
                } else if (balanceRadioButton.isChecked() && !CheckUtils.isNull(mPayInfo)) {
                    balanceRadioButton.setChecked(false);
                }
                this.reckonShouldPrice();
                break;
            case R.id.preferential_radio_layout: //点击了优付卡布局
                if (!preferentialRadioButton.isChecked() && !CheckUtils.isNull(mPayInfo)) {
                    preferentialRadioButton.setChecked(true);
                    if(!uPayCard.getUseCoupon()){
                        //设置与优惠卷不能同时使用
                        tvCouponAmt.setTextColor(getResources().getColor(R.color.txt_gray));
                        couponAmtLayout.setEnabled(false);
                        tvCouponAmt.setText("不能与优付卡同时使用");
                    }
                    balanceRadioButton.setChecked(false);
                    balanceShouldPice.setText("");
                } else if (preferentialRadioButton.isChecked() && !CheckUtils.isNull(mPayInfo)) {
                    preferentialRadioButton.setChecked(false);
                    if(!couponAmtLayout.isEnabled()){
                        couponAmtLayout.setEnabled(true);  //设置能用
                        this.setCouponsStyle(mPayInfo.getCpnRelId(),mPayInfo.getCouponAmt());
                    }
                }
                setUpayStyles();
                break;
            case R.id.easy_recharge:
                showBalanceDialog();
                break;
            case R.id.recharge_dialog_layout:
                showRechargeDialog();
                break;
            case R.id.print_btn:/*打印订单*/
                if (CheckUtils.isMIUIDevices()) {
                    mvpPresenter.printReceipt(_mActivity, orderId);
                } else if (CheckUsbDeviceUtils.isReceipt()) {/*小票*/
                    mvpPresenter.printReceipt(_mActivity, orderId);

                }


                break;
            case R.id.storage_btn:/*返回上一次页面*/
                finish();
                break;


            case R.id.ordier_list_btn:/*订单列表*/
                popTo(GatheringFragment.class, true, new Runnable() {
                    @Override
                    public void run() {
                        start(OrderManageFragment.newInstance("", ""), SINGLETASK);

                    }
                });


                break;
            case R.id.ordier_details_btn:/*订单详情*/
                popTo(GatheringFragment.class, true, new Runnable() {
                    @Override
                    public void run() {
                        start(OrderQuiryDetailFragment.newInstance(orderId, ""), SINGLETASK);

                    }
                });


                break;
            case R.id.place_order_btn:/*下单*/
                popTo(GatheringFragment.class, true, new Runnable() {
                    @Override
                    public void run() {
                        start(CreateOrdersFragment.newInstance(GlobalConsts.CREATE_ORDERS, "下单", "手机号/会员卡号"), SINGLETASK);

                    }
                });

                break;

            case R.id.back_layout:
                finish();
                break;

            case R.id.couponAmt_layout:  //优惠卷
                if (CheckUtils.isNull(mPayInfo))
                    return;
                mvpPresenter.couponList(mPayInfo.getOrderId());

                break;
            case R.id.gathering_layout:  //点击收款
                if (mPayInfo != null && mPayInfo.getShouldPrice() == 0) {
                    if (mPayInfo.isUseUPay()) {  /*优付卡余额充足时 是100百分之百的时候*/
                        mvpPresenter.confirmPay(mPayInfo.getOrderId(), mPayInfo.getPayBalance(), mPayInfo.isUseUPay(), mPayInfo.getCpnRelId());
                    } else {  /*完全余额时*/
                        mvpPresenter.balancePay(mPayInfo.getOrderId(), mPayInfo.getCpnRelId());
                    }
                }
                break;
            case R.id.order_detail_tab1:
                setBackGround(0);
                showHideFragment(mFragments[0]);
                break;
            case R.id.order_detail_tab2:
                setBackGround(1);
                showHideFragment(mFragments[1]);
                break;
            case R.id.order_detail_tab3:
                setBackGround(2);
                showHideFragment(mFragments[2]);
                break;
            case R.id.order_detail_tab4:
                setBackGround(3);
                showHideFragment(mFragments[3]);
                break;
        }
    }


    /**
     * 设置选项卡 背景
     *
     * @param pos
     */
    public void setBackGround(int pos) {
        if (pos == lastPosition) {
            payTabArray[pos].setBackgroundColor(resources.getColor(R.color.white));

        } else {
            payTabArray[pos].setBackgroundResource(R.drawable.gathering_tab_checked);

        }

        for (int i = 0; i < payTabArray.length; i++) {
            if (pos != i) {
                if (i == lastPosition) {
                    payTabArray[i].setBackgroundResource(R.drawable.gathering_right_tab);
                } else {
                    payTabArray[i].setBackgroundResource(R.drawable.gathering_tab);
                }
            }
        }

    }


    /**
     * 用户余额
     *
     * @param mBalanceBean
     * @param isfirstload
     */
    private boolean[] payShowArray = new boolean[4];
    private boolean isEnableAli, isEnableWx, isEnableCash, isEnableUnion;


    private int firstPosition;


    /**
     * 用户余额
     *
     * @param mBalanceBean
     * @param isfirstload
     */
    @Override
    public void useBalanceData(BalanceBean mBalanceBean, boolean isfirstload) {
        if (isRechargeEnter) {
            rechargeBalance.setText("￥" + CheckUtils.isEmptyNumber(mBalanceBean.getBalance()));
        } else {
            this.mBalanceBean = mBalanceBean;
            isEnableAli = mPayInfo.isIsEnableAli();
            isEnableWx = mPayInfo.isIsEnableWx();
            isEnableCash = mPayInfo.isIsEnableCash();
            isEnableUnion = mPayInfo.isEnableOther();
            showPosition();
            showHideFragment(mFragments[firstPosition]);
            fillPayData(mBalanceBean);
        }
    }


    /**
     * 填充充值信息
     *
     * @param item 充值数据对象
     */
    private void fillRechargeData(RechargeBean item) {

        StringBuffer mSendStringBuffer = new StringBuffer();
        mSendStringBuffer.append("充" + CheckUtils.isEmptyNumber(item.getAmount()) + "元");
        if (item.isIsSendAmt()) {
            mSendStringBuffer.append("  送" + CheckUtils.isEmptyNumber(item.getGiftAmount()) + "元");
        }
        rechargeDialogName.setText(mSendStringBuffer.toString());
        rechargeAmount = CheckUtils.isEmptyNumber(item.getAmount());
        setRechargePiceStyles(rechargeAmount, false);
        StringBuffer mStringBuffer = new StringBuffer();
        if (item.isIsSendPoint()) {/*积分*/
            mStringBuffer.append("送" + item.getGiftPoint() + "积分,");

        }
        if (item.isIsSendCoupon()) {/*优惠券*/
            mStringBuffer.append("送" + item.getCouponCnt() + "优惠券,");

        }
        if (item.isIsSendCard()) {/*会员卡*/
            mStringBuffer.append("可获得" + item.getCardName() + "一张,");
        }

        String sendMsg = mStringBuffer.toString();
        if (sendMsg.endsWith(",")) {
            rechargeDialogMore.setText("(" + sendMsg.substring(0, sendMsg.length() - 1) + ")");
        } else {
            rechargeDialogMore.setText("");
        }
    }
    /**
     * 设置优惠卷的样式
     * couponId 优惠卷id
     *tvCouponAmt 优惠卷金额
     */
    private  void  setCouponsStyle(String couponId,int couponAmt){
        if (!TextUtils.isEmpty(couponId) && couponAmt!=0){
            tvCouponAmt.setTextSize(CheckUtils.isMIUIDevices() ? 24 : 36);
            tvCouponAmt.setText("-" + CheckUtils.isEmptyNumber(couponAmt));/*优惠券*/
            tvCouponAmt.setTextColor(getResources().getColor(R.color.warm_red));
        }else {
            tvCouponAmt.setTextColor(getResources().getColor(R.color.txt_gray));
            tvCouponAmt.setText("无可用");
        }
    }
    /**
     * 设置会员卡余额和优付卡是否能用
     */
    private  void  setVipCardBalanceAndPreferentialPayEnabled(){
        //会员卡余额布局显示
        if(vipCardBalanceLayout.getVisibility()==View.VISIBLE){
            if(vipCardBalanceLayout.isEnabled()){
                if(mPayInfo.getCouponAmt()>= mPayInfo.getPayablePrice()){   //如果优惠卷金额大于等于 应收款金额 就不能用会员卡余额支付
                    enabledImageview.setVisibility(View.VISIBLE);
                    enabledCheckBox.setVisibility(View.GONE);
                    enabledCheckBox.setChecked(false);
                }else if(mPayInfo.getCpnUseBalance()==1){ // 等于1 允许使用会员卡余额金额
                    enabledImageview.setVisibility(View.GONE);
                    enabledCheckBox.setVisibility(View.VISIBLE);
                }else if(mPayInfo.getCpnUseBalance()==0){     //不允许使用会员卡余额金额
                    enabledImageview.setVisibility(View.VISIBLE);
                    enabledCheckBox.setVisibility(View.GONE);
                    enabledCheckBox.setChecked(false);
                }
            }
        }else if(payTypeTwo.getVisibility()==View.VISIBLE) {  //余额支付和优付卡布局显示
            if (mPayInfo.getCouponAmt() >= mPayInfo.getPayablePrice()) {   //如果优惠卷金额大于等于
                if (balanceRadioLayout.isEnabled()) {
                    //余额支付能用的才设置
                    tvBalancePay.setTextColor(getResources().getColor(R.color.txt_gray));
                    tvUsableBalance.setTextColor(getResources().getColor(R.color.txt_gray));
                    balanceRadioButton.setButtonDrawable(R.drawable.pay_check_endle);
                    balanceShouldPice.setText("");
                    balanceRadioLayout.setClickable(false);
                    balanceRadioButton.setChecked(false);
                }
                if (preferentialRadioLayout.isEnabled()) {
                    //优付卡支付能用才设置
                    preferentialMsg.setTextColor(getResources().getColor(R.color.txt_gray));
                    preferentialBalance.setTextColor(getResources().getColor(R.color.txt_gray));
                    preferentialPayRatio.setTextColor(getResources().getColor(R.color.txt_gray));
                    preferentialRadioButton.setButtonDrawable(R.drawable.pay_check_endle);
                    preferentialShouldPice.setText("");
                    preferentialRadioLayout.setClickable(false);
                    preferentialRadioButton.setChecked(false);
                }
            } else if (mPayInfo.getCpnUseBalance() == 1) { // 等于1 允许使用会员卡余额金额
                //余额支付能用就设置
                if (balanceRadioLayout.isEnabled()) {
                    if (!balanceRadioLayout.isClickable()) {
                        balanceRadioButton.setButtonDrawable(R.drawable.pay_checkbox_style);
                        tvBalancePay.setTextColor(getResources().getColor(R.color.black));
                        tvUsableBalance.setTextColor(getResources().getColor(R.color.black));
                        balanceRadioLayout.setClickable(true);  //设置可用点击
                    }
                }
                if (preferentialRadioLayout.isEnabled()) { //能用就设置
                    if (!preferentialRadioLayout.isClickable()) {
                        preferentialMsg.setTextColor(getResources().getColor(R.color.black));
                        preferentialBalance.setTextColor(getResources().getColor(R.color.black));
                        preferentialPayRatio.setTextColor(getResources().getColor(R.color.black));
                        preferentialRadioButton.setButtonDrawable(R.drawable.pay_checkbox_style);
                        preferentialRadioLayout.setClickable(true); //设置可用点击
                    }
                }
            } else if (mPayInfo.getCpnUseBalance() == 0) {     //不允许使用会员卡余额金额
                if (balanceRadioLayout.isEnabled()) {
                    if (balanceRadioLayout.isClickable()) {
                        balanceShouldPice.setText("");
                        tvBalancePay.setTextColor(getResources().getColor(R.color.txt_gray));
                        tvUsableBalance.setTextColor(getResources().getColor(R.color.txt_gray));
                        balanceRadioButton.setButtonDrawable(R.drawable.pay_check_endle);
                        balanceRadioLayout.setClickable(false);
                        balanceRadioButton.setChecked(false);
                    }
                }
                if (preferentialRadioLayout.isEnabled()) { //能用就设置
                    if (!preferentialRadioLayout.isClickable()) {
                        preferentialMsg.setTextColor(getResources().getColor(R.color.black));
                        preferentialBalance.setTextColor(getResources().getColor(R.color.black));
                        preferentialPayRatio.setTextColor(getResources().getColor(R.color.black));
                        preferentialRadioButton.setButtonDrawable(R.drawable.pay_checkbox_style);
                        preferentialRadioLayout.setClickable(true); //设置可用点击
                    }
                }
            }
        }
    }

    /**
     * 填充支付信息
     *
     * @param mBalanceBean 用户的余额信息
     */
    private void fillPayData(BalanceBean mBalanceBean) {
        Integer intModifyPrice = mPayInfo.getModifyPrice(); /*修改金额*/
        isExistCpnRelId = CheckUtils.isEmpty(mPayInfo.getCpnRelId());
        carriage.setText("¥ " + CheckUtils.isEmptyNumber(mPayInfo.getCarriage()));/*取送费*/
        orderPrice.setText("¥ " + CheckUtils.isEmptyNumber(mPayInfo.getOrderPrice()) + "");/*订单衣物金额*/
        paymentPrice.setText("¥ " + CheckUtils.isEmptyNumber(mPayInfo.getPayablePrice())); /*支付金额*/
        setModifyPrice(intModifyPrice); /*设置修改金额*/
        totalBalance = mBalanceBean.getBalance();  //获得可用余额
        //获得优付卡所有数据
        uPayCard = mPayInfo.getUPayCard();
        //设置优惠卷的样式
        this.setCouponsStyle(mPayInfo.getCpnRelId(),mPayInfo.getCouponAmt());
        if (!CheckUtils.isNull(uPayCard)) {   /*是否存在优付卡支付*/
           /*可用余额*/
            vipCardBalanceLayout.setVisibility(View.GONE);
            //显示余额支付和优付卡支付
            payTypeTwo.setVisibility(View.VISIBLE);
            if (totalBalance <= 0) {
                tvBalancePay.setTextColor(getColors(R.color.txt_gray));
                tvUsableBalance.setTextColor(getColors(R.color.txt_gray));
                balanceRadioButton.setButtonDrawable(R.drawable.pay_check_endle);
                balanceRadioLayout.setEnabled(false);
            } else {
                balanceRadioButton.setChecked(true);
            }
            //设置余额支付的可用余额
            tvUsableBalance.setText("可用余额 " + CheckUtils.isEmptyNumber(totalBalance) + "元");
           /*判断是否能使用优付卡支付*/
            if (uPayCard.getBalance() <= 0 || uPayCard.getPayRatio() == 0|| !uPayCard.getIsEnable()) {
                preferentialMsg.setTextColor(getResources().getColor(R.color.txt_gray));
                preferentialBalance.setTextColor(getResources().getColor(R.color.txt_gray));
                preferentialPayRatio.setTextColor(getResources().getColor(R.color.txt_gray));
                preferentialRadioButton.setButtonDrawable(R.drawable.pay_check_endle);
                preferentialRadioLayout.setEnabled(false);
            }
            this.setVipCardBalanceAndPreferentialPayEnabled();
            preferentialBalance.setText("余额 " + CheckUtils.isEmptyNumber(uPayCard.getBalance()) + "元");
            preferentialPayRatio.setText("支付比例 " + uPayCard.getPayRatio() + "%");
            reckonShouldPrice();
        } else {
            if(totalBalance<=0){
                //会员卡余额不可用
                enabledImageview.setVisibility(View.VISIBLE);
                enabledCheckBox.setVisibility(View.GONE);
                vipCardBalanceLayout.setEnabled(false);  //静止使用
            }
            this.setVipCardBalanceAndPreferentialPayEnabled();
            ViewGroup.LayoutParams mParams = clothLayout.getLayoutParams();
            mParams.height = DensityUtils.dip2px(_mActivity, 330);
            clothLayout.setLayoutParams(mParams);
            usableBalance.setText("可用余额 " + CheckUtils.isEmptyNumber(totalBalance) + "元");
            reckonShouldPrice();
        }
    }

    private void setModifyPrice(Integer intModifyPrice) {
        if (CheckUtils.isNull(intModifyPrice)) {  /*修改金额*/
            modifyPriceLayout.setVisibility(View.GONE);
        } else {
            modifyPriceLayout.setVisibility(View.VISIBLE);
            modifyPrice.setText("¥ " + CheckUtils.isEmptyNumber(mPayInfo.getModifyPrice()));
        }
    }


    private RelativeLayout[] payTabArray;

    private void showPosition() {
        payShowArray = new boolean[]{isEnableAli, isEnableWx, isEnableCash, isEnableUnion};
        payTabArray = new RelativeLayout[]{orderDetailTab1, orderDetailTab2, orderDetailTab3, orderDetailTab4};
        boolean first = false;
        lastPosition = 0;
        for (int i = 0; i < payShowArray.length; i++) {
            if (payShowArray[i]) {
                payTabArray[i].setVisibility(View.VISIBLE);
                lastPosition = i;
            }
            if (!first && payShowArray[i]) {
                first = true;
                firstPosition = i;
            }
        }
        setBackGround(firstPosition);

    }

    @Override
    public void loadFail(String msg) {
        T.show(msg);
    }

    @Override
    public void loadCouponList(List<Coupons> mCouponData) {
        showCoupionDialog(mCouponData);
    }


    /**
     *  显示优惠卷对话框
     *
     * @param mCouponData
     */
    private void showCoupionDialog(List mCouponData) {
        CouponsDialogFragment coupons = new CouponsDialogFragment();
        Bundle mBundle = new Bundle();
        mBundle.putBoolean("isPayEnter", true);
        mBundle.putSerializable(ARG_PARAM1, (ArrayList) mCouponData);
        mBundle.putSerializable(ARG_PARAM2, mPayInfo);
        coupons.setArguments(mBundle);
        coupons.show(getChildFragmentManager(), CouponsDialogFragment.class.getName());
    }

    private void showBalanceDialog() {
        BalanceDialogFragment editSex = new BalanceDialogFragment();
        Bundle bundle = new Bundle();
        editSex.setArguments(bundle);
        editSex.show(getChildFragmentManager(), SelectNumDialogFragment.class.getName());
    }


    /**
     * 使用优惠卷
     */
    @Override
    public void userCouponSucceed(Coupons mCoupons) {
        mPayInfo.setCpnRelId(mCoupons.getId());
        mPayInfo.setCouponAmt(mCoupons.getAmount());
        if (preferentialRadioButton.isChecked()) {
            setUpayStyles();
        } else {
            reckonShouldPrice();
        }


    }

    /**
     * 获得支付信息
     * @param mPayInfoBean
     */
    @Override
    public void payInfoData(PayInfoBean mPayInfoBean) {
        isloadSucceed = true;
        frameLayout.setVisibility(View.VISIBLE);
        this.mPayInfo = mPayInfoBean;
        initData();

    }

    /**
     * 打印小票
     *
     * @param mReceiptBean
     */
    @Override
    public void loadReceipt(ReceiptBean mReceiptBean) {
        if (CheckUtils.isMIUIDevices()) {
            PrintMiuiHelper.receiptReceipt(MainActivity.getPrintService(), mReceiptBean);
        } else {
            PrinterReceipt mPrinterReceipt = new PrinterReceipt();
            GpDevice mDevice = new GpDevice();
            mPrinterReceipt.printGp80(mReceiptBean, mDevice);

        }


    }

    /**
     * 充值支付开关
     *
     * @param mRechargeSwitch
     */
    @Override
    public void rechargeShowswitch(PayInfoBean mRechargeSwitch) {
        /*是否能使用支付宝*/
        if (!CheckUtils.isEmpty(mRechargeSwitch.getPaySignList()))
        {
            PayAmountEvent.postHasData(PayAmountEvent.Message.otherRecharge,mRechargeSwitch);
        }
        mRechargeSwitch.getPaySignList();
        isEnableAli = mRechargeSwitch.isIsEnableAli();
        isEnableUnion = mRechargeSwitch.isIsEnableUnion();
        isEnableWx = mRechargeSwitch.isIsEnableWx();
        isEnableCash = mRechargeSwitch.isIsEnableCash();
        frameLayout.setVisibility(View.VISIBLE);
        showPosition();
        showHideFragment(mFragments[firstPosition]);

    }


}
